package com.udi.project.system.user.controller;

import com.udi.common.utils.ServletUtils;
import com.udi.common.utils.StringUtils;
import com.udi.framework.web.controller.BaseController;
import com.udi.framework.web.domain.AjaxResult;
import com.udi.project.business.activate.thread.ActivateCodeThread;
import com.udi.project.business.utils.redis.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证
 * 
 * @author udi
 */
@Controller
public class LoginController extends BaseController
{

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ActivateCodeThread activateCodeThread;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /** 产品有效期校验*/
        String validPeriod = (String) redisUtils.get("period");
        if(validPeriod == null){
            activateCodeThread.reom();
        }
        if("no".equals(redisUtils.get("period"))){
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "login";
        }
        return "certification";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe,HttpServletResponse response) throws IOException {
        if("no".equals(redisUtils.get("period"))){
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
            Subject subject = SecurityUtils.getSubject();
            try
            {
                subject.login(token);
                return success();
            }
            catch (AuthenticationException e)
            {
                String msg = "用户或密码错误";
                if (StringUtils.isNotEmpty(e.getMessage()))
                {
                    msg = e.getMessage();
                }
                return error(msg);
            }
        }
        response.sendRedirect("certification");
        return error("你的产品已过期");
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }
}
